package com.wzx.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzx.user.mapper.NotesMapper;
import com.wzx.user.mapper.RedPkgMapper;
import com.wzx.user.mapper.WalletMapper;
import com.wzx.user.pojo.Notes;
import com.wzx.user.pojo.RedPkg;
import com.wzx.user.pojo.Wallet;
import com.wzx.user.service.RedPkgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author wzx
 * @version 1.0
 * @date 2023/5/17 - 17:45
 * @description 标题
 */
@Slf4j
@Service
public class RedPkgServiceImpl extends ServiceImpl<RedPkgMapper, RedPkg> implements RedPkgService {

    @Autowired
    private RedPkgMapper redPkgMapper;

    @Autowired
    private WalletMapper walletMapper;

    @Autowired
    private NotesMapper notesMapper;

    @Override
    public void backPrice() {
        List<RedPkg> redPkgs = redPkgMapper.queryBackList();

        for (RedPkg redPkg : redPkgs) {
            //1，给用户添加余额
            QueryWrapper<Wallet> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", redPkg.getSendId());
            Wallet wallet = walletMapper.selectOne(queryWrapper);
            wallet.setBalance(wallet.getBalance() + redPkg.getSurplusAmount());
            walletMapper.updateById(wallet);

            //2，添加历史记录
            Notes notes = new Notes();
            notes.setType("红包:未领取红包退款");
            notes.setPrice(redPkg.getSurplusAmount());
            notes.setUserId(redPkg.getSendId());
            notes.setState("1");
            notes.setMethod("7");
            notes.setRedPkgId(redPkg.getRedPkgId());
            notes.setRedPkgType(redPkg.getType());
            notesMapper.insert(notes);
            log.info("用户{}已获取到{}（分）的退款", redPkg.getSendId(), redPkg.getSurplusAmount());

            //3，修改红包信息
            //redPkg.setSurplusAmount(0);
            //redPkg.setSurplusNum(0);
            redPkg.setDataState("3");
            redPkg.setLootAllTime(new Date());
            redPkgMapper.updateById(redPkg);
            log.info("红包{}的信息已被更改", redPkg.getRedPkgId());
        }
    }
}
